package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FaceEngineService faceEngineService;

    public boolean loginReginfo(Map<String, String> param, String token) {
        User user = userService.checkUserByToken(token);
        if(null==user)
            return false;
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equals(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));
        return this.userInfoMapper.insert(userInfo) == 1;
    }

    public boolean saveUserLogo(MultipartFile headPhoto, String token) throws IOException {
        User user = userService.checkUserByToken(token);
        if(user == null)
            return false;
        boolean flag = faceEngineService.checkIsPortrait(headPhoto.getBytes());
        if (!flag)
            return false;
        //图片上传到阿里云OSS
        PicUploadResult result = picUploadService.upload(headPhoto);
        if(result.getStatus().equals("done")){
            UserInfo userInfo = new UserInfo();
            userInfo.setLogo(result.getName());
            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserInfo::getUserId,user.getId());
            return userInfoMapper.update(userInfo, wrapper) == 1;

        }
        return false;

    }
}
